package com.domain.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.domain.common.AppLogger;
import com.domain.common.Const;
import com.domain.common.Result;
import com.domain.dao.ContactsMapper;
import com.domain.dao.PublishMapper;
import com.domain.dao.UsersAddFriendsMapper;
import com.domain.dao.UsersMapper;
import com.domain.pojo.Contacts;
import com.domain.pojo.Publish;
import com.domain.pojo.Users;
import com.domain.pojo.UsersAddFriends;
import com.domain.service.BusinessCardService;
import com.domain.utils.DateUtils;
import com.domain.utils.NotNullUtils;
import com.domain.utils.UUIDUtils;
import com.domain.utils.jiguang.Jdpush;
import com.domain.utils.wyyx.IMSndmsg;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class BusinessCardServiceImpl implements BusinessCardService {

    /**
     * 日志
     */
    private static Logger logger = AppLogger.getLogger(BusinessCardServiceImpl.class.getSimpleName(), Level.INFO.toString(), true);

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private PublishMapper publishMapper;
    @Autowired
    private UsersAddFriendsMapper usersAddFriendsMapper;

    @Autowired
    private ContactsMapper contactsMapper;

    /**
     * 获取个人名片
     *
     * @param userId
     * @return
     */
    @Override
    public Result getUsersCards(String userId, String chUserId) {
        Map<String, Object> maps = new HashMap<>();
        Users user = usersMapper.selectByPrimaryKey(chUserId);
        /*获取最新一条发布帮忙*/
        List<Publish> publishs = publishMapper.selectPublishByUserId(user.getId());
        if (publishs.size() > 0) {
            maps.put("publishTitle", publishs.get(0).getTitle());
        } else {
            maps.put("publishTitle", "");
        }
        //判断是否是好友
        Contacts cs = contactsMapper.selectByUsersIdAndFriendsId(userId, chUserId);
        if (NotNullUtils.isNotNullObject(cs)) {
            maps.put("isitFriends", "true");
        }
        maps.put("id", user.getId());
        maps.put("nickname", user.getNickname());
        maps.put("name", user.getName());
        maps.put("phone", user.getPhone());
        maps.put("gender", user.getGender());
        maps.put("headImage", user.getHeadImage());
        maps.put("birthday", DateUtils.getAgeByBirthDay(user.getBirthday()));
        maps.put("industry", user.getIndustry());
        maps.put("personalLabel", NotNullUtils.sliptList(user.getPersonalLabel()));
        maps.put("city", user.getCity());
        maps.put("image", NotNullUtils.sliptList(user.getImage()));
        maps.put("spectralValue", user.getSpectralValue());
        maps.put("token", user.getSpareOne());
        return Result.success("操作成功", maps);
    }

    /**
     * 加好友
     *
     * @param userId
     * @param friendId
     * @return
     */
    @Override
    public Result addFriends(String userId, String friendId, String groupId, String type) throws IOException {
        //获取加好友用户得讨论组
        Users users = usersMapper.selectByPrimaryKey(userId);
        String msg = "";
        String lable = "";
        String res = IMSndmsg.queryDetailTeam(groupId, "1");
        JSONObject jsonObject = JSONObject.parseObject(res);
        JSONObject j = JSONObject.parseObject(jsonObject.get("tinfo").toString());
        if ("2".equals(type)) {
            msg = "来自" + j.get("tname") + "群";
            lable = j.get("tname").toString();
        }
        if ("1".equals(type)) {
            msg = users.getName() + "请求加你为好友";
            lable = users.getName();
        }
        //推送加好友信息
        Jdpush.sendToAliasList(friendId, msg, "pushId", UUIDUtils.getRandomUUID(), "pushType", "", "biTypeKey", Const.ADD_FRIENDS, "好友请求");
        //判断是否添加过记录
        UsersAddFriends ud = usersAddFriendsMapper.selectByFriends(userId, friendId);
        if (!NotNullUtils.isNotNullObject(ud)) {
            //生成添加朋友记录
            UsersAddFriends friends = new UsersAddFriends();
            friends.setId(UUIDUtils.getRandomUUID());
            friends.setCreatTime(new Date());
            friends.setUsersId(userId);
            friends.setFriendsId(friendId);
            friends.setType(Const.REQUEST_FRIENDS);
            friends.setSpareOne(msg);
            friends.setSpareTwo(lable);
            usersAddFriendsMapper.insertSelective(friends);
        }
        return Result.success("操作成功");
    }

    /**
     * 发消息
     *
     * @param userId 发送者id
     * @param ope    0：点对点个人消息，1：群消息（高级群），其他返回414
     * @param to     ope==0是表示accid即用户id，ope==1表示tid即群id
     * @param type   0 表示文本消息,
     *               1 表示图片，
     *               2 表示语音，
     *               3  表示视频，
     *               4 表示地理位置信息，
     *               6 表示文件，
     *               100 自定义消息类型（特别注意，对于未对接易盾反垃圾功能的应用，该类型的消息不会提交反垃圾系统检测）
     * @param body   发送得内容最大长度5000字符，为一个JSON串
     * @return
     */
    @Override
    public Result sendMessage(String userId, String ope, String to, String type, String body) throws IOException {
        String result = IMSndmsg.sendMsg(userId, ope, to, type, body);
        return Result.success(result);
    }


}
